package com.idp.web.controller;
import com.idp.web.entity.User;
import com.idp.web.service.IUserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idp.common.base.BaseController;
import com.idp.common.persistence.Page;
import com.idp.common.util.ValidateUtils;

import net.sf.json.JSONObject;

/**
 * 用户controller
 * @author xubinren
 * @version 1.0
 * @date 2018/3/1
 */
@Controller
@RequestMapping("/currentUser")
public class UserController extends BaseController {

	private Logger logger = Logger.getLogger(UserController.class);

	@Resource
	private IUserService userService;
	
	/**
	 * 	初始化查询页面
	 *
	 * @return
	 */
	@RequestMapping("/init")
	public String init(){
		return "/userSearch";
	}
	
	/**
	 * 	分页查询
	 * </pre>
	 * 
	 * @param user
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public String list(User user,Page<User> page,HttpServletRequest request){
		try {
			request.setAttribute("page", userService.findByPage(user, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
		return "/userList";
	}

	/**
	 * 
	 * 	新增修改页面初始化
	 *
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/user")
	public String user(String id,HttpServletRequest request){
		try {
			if(ValidateUtils.isNotEmpty(id)){
				User user = userService.getById(id);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "/user";
	}
	
	/**
	 * 	保存
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(User user){
		JSONObject json = new JSONObject();
		try {
			// 修改
			if(ValidateUtils.isNotEmpty(user.getId())){
				userService.update(user);
			}
			// 新增
			else{
				userService.add(user);
			}
			json.put("result", "save_success");
		} catch (Exception e) {
			
			logger.error(e.getMessage(), e);
			json.put("result", "save_fail");
		}
		return json.toString();
	}
	
	/**
	 * 	删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(String id){
		JSONObject json = new JSONObject();
		try {
			userService.delete(id);
			json.put("result", "delete_success");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("result", "delete_fail");
		}
		return json.toString();
	}
}
